/*
 *  Copyright 2008 The MITRE Corporation (http://www.mitre.org/). All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.mitre.mrald.analysis;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;

import org.mitre.mrald.util.Config;

public class MitreFD extends MitreAnalysis
{
    private Process extProcess = null;
	private String smithersExe = Config.getProperty( "BasePath" ) + "/WEB-INF/smithers.exe";

	private String parameter_f;
	private String parameter_t;
	private String parameter_a;
	private String parameter_s;
	private String parameter_c;
	private String outputFile;


    public MitreFD() {
		super();
	}

    protected void performAnalysis( String template_file, String data_file ) throws AnalysisManagerException
    {
		parameter_f = (msg.getValue( "parameter_f" ))[0];
		parameter_t = (msg.getValue( "parameter_t" ))[0];
		parameter_a = (msg.getValue( "parameter_a" ))[0];
		parameter_s = (msg.getValue( "parameter_s" ))[0];
		parameter_c = (msg.getValue( "parameter_c" ))[0];
		outputFile = System.getProperty( "java.io.tmpdir" ) + "/" + msg.getUserId() + System.currentTimeMillis() + ".out";

		String args = "";
		args += " -f " + parameter_f;
		args += " -t " + parameter_t;
		args += " -a " + parameter_a;
		args += " -c " + parameter_c;
		if ( ! ( parameter_s == null || parameter_s.equals( "null" ) ) )
			args += " -s";
		args += " -n " + templateFile;
		args += " -i " + dataFile;
		args += " -o " + outputFile;

		try
		{
			extProcess = Runtime.getRuntime().exec( smithersExe + args );
			extProcess.waitFor();
		}
		catch ( IOException ioe )
		{
			throw new AnalysisManagerException( ioe.getMessage() );
		}
		catch ( InterruptedException ie )
		{
			throw new AnalysisManagerException( ie.getMessage() );
		}
    }

    protected void displayResults() throws AnalysisManagerException
    {
		PrintWriter out = msg.getOutPrintWriter();
		String line;
		BufferedReader brin;

		try
		{
			brin = new BufferedReader( new FileReader( outputFile ) );

			while ( ( line = brin.readLine() ) != null )
				out.println( line );

			brin.close();
		}
		catch ( FileNotFoundException fne )
		{
			throw new AnalysisManagerException( fne.getMessage() );
		}
		catch ( IOException ioe )
		{
			throw new AnalysisManagerException( ioe.getMessage() );
		}
    }
}

